<?php
class RandomImageHelper extends AppHelper {
	
	var $helpers = array('Html');

	function getImage($path, $options = false) {
		//option defaults
		if(!isset($options['title'])) :
			$options['title'] = '';
		endif;
		if(!isset($options['justTheFilename'])) :
			$options['justTheFilename'] = false;
		endif;
		
		//note that $path is relative to the webroot
		if(substr($path, -1) != '/') :
			$path = $path.'/';
		endif;		
		$folder = APP . '/webroot' . $path;

		//a list of allowed extensions
	    $extList = array();
		$extList['gif'] = 'image/gif';
		$extList['jpg'] = 'image/jpeg';
		$extList['jpeg'] = 'image/jpeg';
		$extList['png'] = 'image/png';

		$img = null;

		//open the folder and get the contents
		$fileList = array();
		$handle = opendir($folder);
		while(false !== ($file = readdir($handle))) :
			$file_info = pathinfo($file);
			if(isset($extList[strtolower($file_info['extension'])])) :
				$fileList[] = $file;
			endif;
		endwhile;
		closedir($handle);

		// pick out a random image
		if (count($fileList) > 0) :
			$imageNumber = time() % count($fileList);
			$img = $this->Html->base.$path.$fileList[$imageNumber];
		endif;
		
		if($options['justTheFilename']) :
			return array('fullPath' => $img, 'filename' => $fileList[$imageNumber]);
		else :
			return $this->output(
				'<img src = "' . $img . '" alt = "' . $options['title'] . '" />'
			);
		endif;
    } // getImage
}
?>